package com.zwj.batch.config.test;

import com.zwj.batch.core.ResouceCount;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * 1>有一个资源类，里面有2个属性：总数：totalCount = 100， 读取数：readCount = 0
 * 2>设计2个步骤，step1 用于叠加readCount 模拟从数据库中读取资源， step2 用于执行逻辑
 * 3>当totalCount  == readCount  时，为正常情况，正常结束。如果不等时，为异常状态。此时不执行step2，直接停止作业。
 * 4>修复数据，在从step1开始执行，并完成作业
 * Step 步骤监听器方式
 *
 * @author 张文接
 * @version 1.0
 * @createTime 2023-06-25 09:40:00
 */
//@Configuration
public class BatchConfig16 {
    private final int readCount = 100; //模拟只读取50个
    @Resource
    private JobBuilderFactory jobBuilderFactory;
    @Resource
    private StepBuilderFactory stepBuilderFactory;

    @Bean
    public Tasklet tasklet1() {
        return new Tasklet() {
            @Override
            public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
                for (int i = 0; i < readCount; i++) {
                    System.out.println("---------------step1执行-" + (i + 1) + "------------------");
                    ResouceCount.READ_COUNT++;
                }

                if (ResouceCount.TOTAL_COUNT != ResouceCount.READ_COUNT) {
                    chunkContext.getStepContext().getStepExecution().setTerminateOnly();
                }
                return RepeatStatus.FINISHED;
            }
        };
    }

    @Bean
    public Tasklet tasklet2() {
        return new Tasklet() {
            @Override
            public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
                System.err.println("step2执行了.......");
                System.err.println("readCount:" + ResouceCount.READ_COUNT + ", totalCount:" + ResouceCount.TOTAL_COUNT);
                return RepeatStatus.FINISHED;
            }
        };
    }

    @Bean
    public Step step1() {
        return stepBuilderFactory
                .get("step1")
                .tasklet(tasklet1())
                .allowStartIfComplete(true) //允许重启
                .build();
    }

    @Bean
    public Step step2() {
        return stepBuilderFactory
                .get("step2")
                .tasklet(tasklet2())
                .build();
    }

    @Bean
    public Job job() {
        return jobBuilderFactory.get("job-stop-job")
                .start(step1())
                .next(step2())
                .build();
    }
}
